<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>FLIP 动画</title>
  <style>
    * {
      margin: 0;
      padding: 0;
      box-sizing: border-box;
    }
    ul, li {
      list-style: none;
    }
    button {
      height: 35px;
      line-height: 35px;
      background-color: #04d1d1;
      margin: 10px;
    }
    .container {
      margin: 10px;
      display: flex;
    }
    .container li {
      width: 50px;
      height: 50px;
      text-align: center;
      line-height: 50px;
      margin-left: 10px;
    }
    .item{
      background-color: #f02e2e;
    }
    .item {
      background-color: chocolate;
    }
    .item {
      background-color: #e9ec05;
    }
    .item {
      background-color: #099;
    }
    .item {
      background-color: #10d4ee;
    }
  </style>
</head>
<body>
  <button class="shuffle">FLIP Shuffle</button>
  <ul class="container">
    <li class="item">01</li>
    <li class="item">02</li>
    <li class="item">03</li>
    <li class="item">04</li>
    <li class="item">05</li>
  </ul>
  <script>
    const container = document.querySelector('.container');
    const shuffle1 = document.querySelector('.shuffle');

    // 记录开始位置信息
    function record(container) {
      const all = [...container.children]
      all.forEach((item, i) => {
        const rect = item.getBoundingClientRect()
        item.startX = rect.left
      })
    }
   

    function change() {
      const all = [...container.children]
      const len = all.length
      all.forEach((item, i) => {
        const newIndex = Math.floor(Math.random() * len)
        if (newIndex !== i) {
          const nextDOM = item.nextElementSibling
          container.insertBefore(item, all[newIndex])
          container.insertBefore(all[newIndex], nextDOM)
        }
      })
    }
    function play(container) {
      const all = [...container.children]
      const len = all.length
      all.forEach((item, i) => {
        const rect = item.getBoundingClientRect()
        const currentX = rect.left
        item.animate([
          { transform: `translateX(${item.startX - currentX}px)` },
          { transform: 'translateX(0px)' }
        ], {duration: 600})
      })
    }
    shuffle1.onclick = () => {
      record(container)
      change();
      play(container)
    }

    function delay(duration = 1000) {
      const start = Date.now()
      while(Date.now() - start < duration) {}
    }
  </script>
</body>
</html>